<template>
  <div class="sub-category">
    <!-- 面包屑 -->
    <sub-bread></sub-bread>
    <!-- 筛选区 -->
    <div class="goods-list">
      <sub-filter @changeFilter="changeFilter"></sub-filter>
      <!-- 排序 -->
      <sub-sort @changeSort="changeSort"></sub-sort>
      <!-- 列表 -->
      <ul>
        <li v-for="goods in goodsList" :key="goods.id">
          <sub-goods :goods="goods" />
        </li>
      </ul>
      <!-- 加载更多 -->
      <infinite-loading
        @infinite="getData"
        :loading="loading"
        :finished="finished"
      ></infinite-loading>
    </div>
  </div>
</template>

<script>
import SubBread from "./components/SubBread.vue";
import SubFilter from "./components/SubFilter.vue";
import { ref, watch } from "vue";
import { useRoute } from "vue-router";
import SubSort from "./components/SubSort.vue";
import SubGoods from "./components/SubGoods.vue";
import { findSubCategoryGoods } from "api/home.js";
export default {
  components: {
    SubBread,
    SubFilter,
    SubSort,
    SubGoods,
  },
  name: "SubCategory",
  setup() {
    const route = useRoute();
    //加载中
    const loading = ref(false);
    //是否全部加载完
    const finished = ref(false);
    const goodsList = ref([]);
    let requestParams = {
      page: 1,
      pageSize: 20,
      categoryId: null,
    };
    const getData = () => {
      loading.value = true;
      requestParams.categoryId = route.params.id;
      findSubCategoryGoods(requestParams).then((res) => {
        if (res.result.items.length) {
          // 得解构push进去
          goodsList.value.push(...res.result.items);
          requestParams.page++;
        } else {
          //没有数据了，全部加载完了
          finished.value = true;
        }
        loading.value = false;
      });
    };
    watch(
      () => route.params.id,
      (newValue) => {
        if (newValue && `/category/sub/${newValue}` === route.path) {
          goodsList.value = [];
          requestParams.page = 1;
          finished.value = false;
          // getData();
        }
      },
      {
        // immedient,
      }
    );
    //更改排序请求
    const changeSort = (sortParams) => {
      finished.value = false;
      //请求参数合并
      requestParams = { ...requestParams, ...sortParams };
      requestParams.page = 1;
      goodsList.value = [];
    };
    //更改筛选请求
    const changeFilter = (filterParams) => {
      finished.value = false;
      requestParams = { ...requestParams, ...filterParams };
      requestParams.page = 1;
      goodsList.value = [];
    };
    return { getData, loading, finished, goodsList, changeSort, changeFilter };
  },
};
</script>

<style lang="less" scoped>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
